package br.perfiman.utils;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ServiceLocator {
	private static ServiceLocator locator;

	private InitialContext initialContext;

	private ServiceLocator() {
		try {
			Hashtable<String, String> t = new Hashtable<String, String>();
			t.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
			t.put(Context.PROVIDER_URL, "localhost");
			t.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
			initialContext = new InitialContext(t);
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}

	public static ServiceLocator getInstance() {
		if (locator == null) {
			locator = new ServiceLocator();
		}
		return locator;
	}

	protected Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException(
				"Nao e possivel clonar o ServiceLocator!");
	}

	public Object get(String jndiName) throws Exception {
		try {
			Object result = null;
			result = initialContext.lookup(jndiName);
			if (result == null) {
				if (result == null) {
					throw new NamingException();
				}
			}
			return result;
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return null;
	}
}